//
//  SWAccountManager.swift
//  MissMedia
//
//  Created by linhan on 16/3/31.
//  Copyright © 2016年 Miss. All rights reserved.
//

import Foundation

private let _manager = SWAccountManager()
class SWAccountManager:NSObject,SWAPIComponent
{
    private var _refreshIntervalID:String = ""
    private var _setup:Bool = false
    var account:SWMainAccount?
    
    private var _accountPath:String{
        return (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).valueAt(0) ?? "") + "/ac.data"
    }
    
    var logined:Bool{
        if let account = account,
           let uid = account.uid , uid != "",
           let phone = account.phone , phone != ""
        {
            return true
        }
        return false
    }
    
    class func sharedManager() -> SWAccountManager
    {
        return _manager
    }
    
    override init()
    {
        super.init()
        accountSetup()
        NotificationCenter.default.addObserver(self, selector: #selector(tokenExpireNotification), name: NotificationName.TokenExpire, object: nil)
    }
    
    func setup()
    {
        if !_setup
        {
            _setup = true
            
        }
    }
    
    //Token有效性检查
    func tokenAvailabilityCheck(successCallback:(()->Void)? = nil, failCallback:((NSError)->Void)? = nil)
    {
        guard let account = account else{
            failCallback?(SWError.TokenInvalidError)
            return
        }
        
        
        //TODO 接口故障,所以直接返回
        loginSuccess(account: account)
        successCallback?()
        return
        
        
        let req = SWUserInfoFetchReq()
        req.callbackOnMainThread = false
        req.successCallback = {[weak self] response,cache in
            if let data = (response as? SWUserInfoFetchRsp)?.data,
                let account = SWMainAccount(response: data)
            {
                self?.loginSuccess(account: account)
                successCallback?()
            }
            else
            {
                failCallback?(SWError.TokenInvalidError)
            }
        }
        req.failCallback = {[weak self] error in
            if error.code == SWError.TokenInvalidError.code
            {
                self?.clearAccount()
            }
            failCallback?(error)
        }
        load(req)
    }
    
    func logout()
    {
        clearAccount()
    }
    
    
    func loginSuccess(account:SWMainAccount)
    {
        self.account = account
        
        //由于第一次登陆缺少邀请码等信息，需要再调一次获取接口获取
        getUserInfo()
        loadStages()
        save()
        
        SWBookManager.sharedManager().setup()
        
        SWTransactionManager.sharedManager().launch()
        //fetchChildrenInfo(successCallback:nil, failCallback: nil)
        
        SWNotificationCenter.post(name: NotificationName.LoginSuccess)
    }
    
    func update()
    {
        save()
    }
    
    //修改个人信息
    func modifyAccountInfo(key:SWModifyUserInfoKey, value:Any, notify:Bool = false, successCallback:(()->Void)? = nil, failCallback:((NSError)->Void)? = nil)
    {
        let req:SWModifyUserInfoReq = SWModifyUserInfoReq()
        req.setValue(value, forKey: key.rawValue)
        req.successCallback = {[weak self] response,cache in
            self?.account?.setValue(value, forKey: key.rawValue)
            self?.save()
            if notify{
                NotificationCenter.default.post(name: NotificationName.AccountInfoChanged, object: nil, userInfo: [key:value])
            }
            successCallback?()
        }
        req.failCallback = {error in
            failCallback?(error)
        }
        load(req)
    }
    
    //修改孩子信息
    func modifyChildInfo(key:SWModifyUserInfoKey, value:Any, notify:Bool = false, successCallback:(()->Void)? = nil, failCallback:((NSError)->Void)? = nil)
    {
        let req:SWAddChildReq = SWAddChildReq()
        if key == .gender
        {
            req.gender = value as? SWGender
        }
        else
        {
            req.setValue(value, forKey: key.rawValue)
        }
        
        req.successCallback = {[weak self] response,cache in
            let child:SWChild? = (self?.account?.children?.valueAt(0) as? SWChild)
            if key == .gender
            {
                if let gender = value as? SWGender
                {
                    child?.gender = gender
                }
            }
            else
            {
                child?.setValue(value, forKey: key.rawValue)
            }
            
            self?.save()
            if notify{
                NotificationCenter.default.post(name: NotificationName.ChildAccountInfoChanged, object: nil, userInfo: [key:value])
            }
            successCallback?()
        }
        req.failCallback = {error in
            failCallback?(error)
        }
        load(req)
        
    }
    
    //创建孩子
    func createChild(gender:SWGender, name:String, birthday:Date, role:Int, successCallback:(()->Void)? = nil, failCallback:((NSError)->Void)? = nil)
    {
        let req = SWAddChildReq()
        req.screenName = name
        req.gender = gender
        req.birthday = birthday as NSDate
        req.role = role
        req.successCallback = {[weak self] response,cache in
            if let response = response as? SWAddChildRsp,
                let data = response.data
            {
                self?.account?.update(response: data)
            }
            //创建完成后拉取阶段列表
            if let _ = self?.account?.child
            {
                self?.loadStages()
            }
            successCallback?()
        }
        req.failCallback = {error in failCallback?(error) }
        load(req)
    }
    
    private func accountSetup()
    {
        let path:String = _accountPath
        if let account = SWCacheManager.sharedManager().readCache(path) as? SWMainAccount,
           let uid = account.uid , uid != ""
        {
            self.account = account
            
            
        }
    }
    
    func save()
    {
        let path:String = _accountPath
        if let account = account
        {
            SWCacheManager.sharedManager().writeCache(account, path: path)
        }
    }
    
    private func getUserInfo()
    {
        guard let account = account,let uid = account.uid , uid != "" else {
                return
        }
        
        //TODO 获取自己的接口暂时不可用
        /**
        let req:SWMineInfoFetchReq = SWMineInfoFetchReq()
        req.successCallback = {[weak self] response, cache in
            if let response = response as? SWMineInfoFetchRsp,
               let user:SWAuthUserInfoRsp = response.data?.user
            {
                account.familyID = "\(user.familyID ?? 0)"
                account.screenName = user.screenName
                account.avatarURL = user.avatar
                account.phone = user.mobile
                account.gender = SWGender.getGender(responseValue:user.gender)
                self?.save()
            }
        }
        load(req)
         **/
    }
    
    //加载阶段列表
    private func loadStages()
    {
        let req = SWStagesFetchReq()
        req.callbackOnMainThread = false
        req.successCallback = {[weak self] response,cache in
            if let response = response as? SWStagesFetchRsp,
                let stages = response.stages?.flatMap({SWStage(response: $0)})
            {
                SWConfigManager.sharedManager().currentStageID = "\(response.currentStageID ?? 0)"
                SWConfigManager.sharedManager().stages = stages
            }
        }
        load(req)
    }
    
    //获取孩子列表
    func fetchChildrenInfo(successCallback:(([SWChild])->Void)?, failCallback:((NSError)->Void)?)
    {
        let req = SWChildrenFetchReq()
        req.successCallback = {[weak self] response, cache in
            
            var children:[SWChild] = []
            if let response = response as? SWChildrenFetchRsp,
               let childrenRsp = response.children , childrenRsp.count > 0
            {
                children = childrenRsp.flatMap({SWChild(child: $0)})
            }
            if let account = self?.account
            {
                account.children = children
                self?.save()
            }
            successCallback?(children)
        }
        req.failCallback = {[weak self] error in
            failCallback?(error)
        }
        load(req)
    }
    
    
    //清除账号信息
    private func clearAccount()
    {
        account = nil
        SWCacheManager.sharedManager().removeCache(_accountPath)
    }
    
    @objc private func tokenExpireNotification()
    {
        //refreshToken()
    }
    
}
